<template>
	<div class='login'>
		<div class="form-card">
			<h2>项目管理</h2>
			<el-form ref="formRef" :model="formData" :rules="rules" :label-width="formLabelWidth">
				<el-form-item label="账号" prop="account">
					<el-input v-model="formData.account" placeholder="请输入账号" @keyup.enter="onSubmit(formRef)" />
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password
						@keyup.enter="onSubmit(formRef)" />
				</el-form-item>
				<el-form-item v-if="actionType === 'reg'" label="确认密码" prop="confirmPassword">
					<el-input v-model="formData.confirmPassword" type="password" placeholder="请输入密码" show-password
						@keyup.enter="onSubmit(formRef)" />
				</el-form-item>
			</el-form>
			<div class="btn">
				<el-button type="primary" @click="onSubmit(formRef)">立即{{ isLogin ? '登录' : '注册' }}</el-button>
			</div>
			<div class="reg">
				<span>{{ isLogin ? '没有' : '已有' }}账号？</span>
				<span @click="changeType(isLogin ? 'reg' : 'log')">去{{ isLogin ? '注册' : '登录' }}</span>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { login, register } from '@/api/login';
import { useRouter } from 'vue-router';
import { setToken } from '@/utils/auth';

interface RuleForm {
	account: string;
	password: string;
	confirmPassword: string;
}

const validatePass = (rule: any, value: any, callback: any) => {
	if (!value) {
		callback(new Error('请确认密码'))
		return
	}
	if (value === '' || formData.value.password !== value) {
		callback(new Error('两次密码不相同'))
		return;
	}
	callback()
}
const router = useRouter();
const actionType = ref('log')
const formRef = ref<FormInstance>();
const formLabelWidth = ref(80)
const formData = ref({
	account: 'admin',
	password: 'admin',
	confirmPassword: ''
})
const rules = ref<FormRules<RuleForm>>({
	account: [
		{
			required: true,
			message: '请输入账号',
			trigger: 'blur'
		},
	],
	password: [
		{
			required: true,
			message: '请输入密码',
			trigger: 'blur',
		},
	],
	confirmPassword: [{
		required: true,
		validator: validatePass,
		trigger: 'blur'
	}]
})
const isLogin = computed(() => actionType.value === 'log');

const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate(valid => {
		if (valid) {
			const {
				account,
				password
			} = formData.value;
			const api = isLogin.value ? login : register;
			api({
				account,
				password
			}).then((res) => {
				ElMessage.success(`${isLogin.value ? '登录' : '注册'}成功`);
				if (isLogin.value) {
					setToken(res.token);
					router.push('/manage-project')
				} else {
					actionType.value = 'log';
				}
			})
		}
	})
}
const changeType = (type: string) => {
	actionType.value = type;
	formRef.value?.resetFields();
}
</script>
<style lang='scss' scoped>
@import "./index";
</style>
